import { type FC, Fragment } from 'react';
import { View, Text } from 'react-native';
import { useSafeState, useMemoizedFn } from 'ahooks';
import Button from './button';
import styles from './styles';
import type { ConfirmProps } from '../../types';

const Confirm: FC<ConfirmProps> = (props) => {
  const {
    title,
    content,
    onBtnClose,
    onLoading,
    buttons = []
  } = props;

  const total = buttons.length;
  const [loading, setLoading] = useSafeState(false);

  const onLoadingState = useMemoizedFn((loading: boolean) => {
    onLoading(loading);
    setLoading(loading);
  });

  return (
    <View style={styles.wrapper}>
      <View style={styles.content}>
        <Text style={styles.title}>{title}</Text>
        {!!content && <Text style={styles.desc}>{content}</Text>}
      </View>
      {buttons.length > 0 && (
        <View style={styles.buttons}>
          {buttons.map((item, i) => {
            const { key, ...rest } = item;
            const _loading = (() => {
              return item.main && loading;
            })();

            const _disabled = (() => {
              if (item.disabled) return true;
              return !item.main && loading;
            })();

            const onPress = async () => {
              const result = item.onPress?.();
              if (result instanceof Promise) {
                onLoadingState(true);
              }           
              if (await result ?? true) {
                requestAnimationFrame(onBtnClose);
              }
              onLoadingState(false);
            }

            return (
              <Fragment key={key}>
                <Button
                  {...rest}
                  loading={_loading}
                  disabled={_disabled}
                  onPress={onPress}
                />
                {(i + 1 !== total) && (
                  <View style={styles.line} />
                )}
              </Fragment>
            );
          })}
        </View>
      )}
    </View>
  );
}

export default Confirm;